<?php
/**
 * PHP Framework Core JSON Serializer class
 *
 * @author Andrew <andrew@vitche.com>
 * @author Frozen Rain <frozenrain@mail.ru>
 **/

class JSONSerializer {

    /**
     * Builds a JSON representation of a PHP object
     *
     * TODO: Rewrite using IReflectable and other Reflection features
     *
     * @param mixed $object A PHP object which must be converted to JSON
     * @return string A JSON representation of a PHP object
     **/
    public static function toString($object) {

        $strRes = '';
        if (is_array($object)) {
            $strRes .= '[';
            foreach ($object as $value) {
                $strRes .= JSONSerializer::toString($value) . ', ';
            }
            $strRes = trim($strRes, ', ');
            $strRes .= ']';
        } else if (is_object($object)) {
            $strRes .= '{';
            $arVars = get_object_vars($object);
            // TODO: Change to interface checking
            if (method_exists($object, 'toArray')) {
                $arVars = array_merge($arVars, $object->toArray());
            }
            foreach ($arVars as $key => $value) {
                if (!isset($value) || empty($value)) {
                    $strRes .= '"' . $key . '"' . ' : undefined, ';
                } else if (is_string($value)) {
                    $strRes .= '"' . $key . '"' . ' : "' . $value . '", ';
                } else if (is_object($value)) {
                    $strRes .= '"' . $key . '"' . ' : ' . JSONSerializer::toString($value) . ', ';
                } else {
                    $strRes .= '"' . $key . '"' . ' : ' . $value . ', ';
                }
            }
            $strRes = trim($strRes, ', ');
            $strRes .= '}';
        } else if (!isset($object)) {
            $strRes .= 'undefined';
        } else if (is_bool($object)) {
            if ($object) {
                $strRes .= '1';
            } else {
                $strRes .= '0';
            }
        } else {
            $strRes .= '"' . $object . '"';
        }

        return $strRes;
    }
}
?>